package carlyang;

import java.util.Timer;
import java.util.TimerTask;

public class ThreadsTest {
//	public volatile static int count = 0;//volatile使count变量对多线程可见，否则cancle timer线程会一直跑下去。
	public static int count = 0;
	public static Timer timer;
	public static TimerTask timerTask;
	public static Thread thread = null;
	public static boolean stoped = false;
	public static Student student = new Student("yangdong",25);
	public ThreadsTest() {
		// TODO Auto-generated constructor stub
	}

	public void TestThreads() {
		Out.aprintln("---------thread:"+Thread.currentThread().getId()+"-------------");
	}
	public  static void StaticTestThreads() {
		Out.aprintln("---------thread:"+Thread.currentThread().getId()+"-------------");
	}
	/*
	 * timer 线程和 普通thread线程，对同一静态类级变量会有可见性问题
	 * */
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Out.aprintln("Thread name :"+Thread.currentThread().getId());
		student.setName("zhangsan");
		student.setAge(30);
		timer = new Timer("timer");
		timerTask = new TimerTask() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Out.aprintln("Thread name :"+Thread.currentThread().getId());
				Out.aprintln("Cancle timer Thread State:"+(thread==null?"thread = null":thread.getState()));
				Out.aprintln("it is timerTask,count = "+count++);
//				new ThreadsTest().TestThreads();
				ThreadsTest.StaticTestThreads();
				Out.aprintln("student="+student.toString());
			}
		};
		timer.schedule(timerTask, 0, 1000);
		thread  = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Out.aprintln("Thread name :"+Thread.currentThread().getId());
				while (!stoped) {
					
					try {
						Thread.currentThread();
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Out.aprintln("it is Cancle timer Thread,count = "+count);
					ThreadsTest.StaticTestThreads();
					student.setAge(student.getAge()+2);
					Out.aprintln("student="+student.toString());
//					new ThreadsTest().TestThreads();
					if(count >= 10){
						Out.aprintln("Cancle timer");
						timer.cancel();
						stoped = true;
					}
				}
				Out.aprintln("Thread name :"+Thread.currentThread().getName()+" Exit");
			}
		},"Cancle timer Thread");
		thread.start();
	}

}
